package com.test.ai.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/8/18 14:49
 * @modifiedBy:
 * @version: 1.0
 */
@RestController
@RequestMapping("chatModel")
public class ChatModelController {
  @Autowired
  @Qualifier("openAiChatModel")
  private ChatModel chatModel;

  @GetMapping("/chat")
  public String chat(@RequestParam(value = "msg", defaultValue = "你是谁") String msg) {
    return chatModel.call(msg);
  }

  @GetMapping("/chat2")
  public String chat2(@RequestParam(value = "msg", defaultValue = "你是谁") String msg) {
    ChatResponse response =
        chatModel.call(
            new Prompt(
                msg, ChatOptions.builder().model("qwen-plus-2025-07-14").temperature(0.8).build()));
    return response.getResult().getOutput().getContent();
  }

  @GetMapping("/prompt")
  public String prompt(@RequestParam("name") String name, @RequestParam("voice") String voice) {
    String userText =
        """
                    给我推荐北京至少三种美食
                    """;
    UserMessage userMessage = new UserMessage(userText);
    String systemText =
        """
                    你是一个美食咨询助手，可以帮助人们查询美食信息。
                    你的名字是{name},
                    你应该用你的名字和{voice}的饮食习惯回复用户的请求。
                    """;
    SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
    Message systemMessage =
        systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
    Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
    List<Generation> results = chatModel.call(prompt).getResults();
    return results.stream().map(x -> x.getOutput().getContent()).collect(Collectors.joining(""));
  }
}
